import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useConnectionStore } from '@/stores/connection'
import { appoxUtilityBridge } from '@/appox/appox'
import { AppoxTaskBeat } from '@/appox/appox'

export const useContentTransferPanelStore = defineStore('contentTransfer', () => {
  const connectionStore = useConnectionStore()
  const taskBeat = new AppoxTaskBeat()
  
  // 状态
  const uploadTasks = ref([])
  const downloadTasks = ref([])
  const idlePorts = ref([])

  // 动作
  async function updateContentTransferState() {

    if (!connectionStore.isBridgeMode) {
      return;
    }

    taskBeat.handle(async () => {
      let state = await appoxUtilityBridge.getContentTransferState()
      uploadTasks.value = state.uploadTasks
      downloadTasks.value = state.downloadTasks
      idlePorts.value = await appoxUtilityBridge.getIdlePorts()
    })
  }

  async function cancelUploadTask(guid) {
    await appoxUtilityBridge.cancelUploadTask(guid)
  }

  async function cancelDownloadTask(guid) {
    await appoxUtilityBridge.cancelDownloadTask(guid)
  }

  async function removeIdlePort(port) {
    await appoxUtilityBridge.removeIdlePort(port)
  }

  return {
    // 状态
    uploadTasks,
    downloadTasks,
    idlePorts,
    // 动作
    updateContentTransferState,
    cancelUploadTask,
    cancelDownloadTask,
    removeIdlePort
  }
})
